<script setup>
import {
  ElButton,
  ElRow,
  ElCol,
  ElTag,
  ElMessage,
  ElAlert,
  ElInputNumber,
  ElInput,
  ElDatePicker,
  ElUpload,
} from "element-plus";
import {
  fixedInvestReport,
  fixedInvestReportDetails,
  fixedInvestEditDetail,
  fixedInvestDeleteInvestDetail,
} from "@/api/investPaper/";
import CustomModal from "@/components/CustomModal/index";
import { getCurentDate, endsWithAny, transformNumber } from "@/hooks/useCommon";
import { ref, computed, watchEffect } from "vue";
import PreviewPdf from "@/components/PreviewPdf";
import CustomTable from "@/components/CustomTable";
import { useUpload } from "@/hooks/useUpload";
import { getCurentPaperMonth } from "../columns";
import { useStore } from "vuex";
import { recordType } from '@/common/dict/dictCollect'
const props = defineProps({
  init: { type: Object, default: () => ({}) },
  title: { type: String, default: "明细填报" },
  visible: { type: Boolean, default: false },
  onlyEdit: { type: Boolean, default: false },
});
const emit = defineEmits(["update:visible", "finish"]);
const open = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emit("update:visible", val);
  },
});
const columns = [
  {
    label: "款项名称",
    prop: "itemName",
    minWidth: 150,
    slot: true,
    editType: "input",
  },
  {
    label: "类型",
    prop: "type",
    minWidth: 150,
    formatter: (text) => recordType[text]
  },
  {
    label: "支付金额(元)",
    minWidth: 100,
    prop: "paymentAmount",
    slot: true,
    editType: "inputNumber",
  },
  {
    label: "付款时间",
    minWidth: 100,
    prop: "paymentTime",
    slot: true,
    editType: "date",
  },
  {
    label: "支付凭证",
    prop: "paymentFileUrl",
    minWidth: 220,
    editType: "upload",
    slot: true,
  },
  {
    label: "填报人/时间",
    minWidth: 120,
    prop: "createUserName",
    formatter: (t, r) =>
      r.createUserName ? `${r.createUserName}/${r.createTime}` : "-",
  },
];

const rules = {
  nextMonthWork: [
    { required: true, message: "请输入下月工作安排", trigger: "blur" },
  ],
  importantWork: [
    { required: true, message: "请输入本月重点工作", trigger: "blur" },
  ],
};
const store = useStore();
const userId = computed(() => store.state.user.userId);
const { curDay, curMonth, curYear } = getCurentDate();

const currentMonth = computed(() => getCurentPaperMonth());
const uploadRef = ref();
const edits = ref({});
const form = ref();
const dataSource = ref([]);
const isEdit = ref(false);
const previewVisible = ref(false);
const previewUrl = ref("");

const getMonthDetails = async () => {
  const { data } = await fixedInvestReportDetails({
    month: currentMonth.value,
    year: curYear,
    fixedProjectId: props.init.fixedProjectId,
  });
  if(!data) return
  const { details = [], ...rest } = data;
  dataSource.value =
    details?.map((_) => ({
      ..._,
      paymentFileUrl: [{ name: _.paymentFileName, url: _.paymentFileUrl }],
      disabled: !props.onlyEdit,
    })) || [];
  edits.value = { ...rest };
};
watchEffect(() => {
  if (!open.value) return;
  dataSource.value = [];
  edits.value = {};
  isEdit.value = false;
  getMonthDetails();
});

const onUpload = async (value, row) => {
  const { file } = value;
  const typeArry = [
    ".jpg",
    ".png",
    ".bmp",
    ".JPG",
    ".PNG",
    ".BMP",
    ".gif",
    ".GIF",
    ".PDF",
    ".pdf",
  ];
  const type = file.name.substring(file.name.lastIndexOf("."));
  const isfile = typeArry.indexOf(type) > -1;
  if (!isfile) {
    // uploadRef.value.clearFiles();
    uploadRef.value.handleRemove(value.file);
    // row.paymentFileUrl = row.paymentFileUrl || [];

    return ElMessage.error("请上传指定文件类型");
  }

  const { fileUrl } = await useUpload(value);
  value.onSuccess();
  const { name } = value.file;
  const fileInfo = { name, url: fileUrl };
  row.paymentFileUrl = [fileInfo];
};

const onEdit = (row) => {
  dataSource.value.map((item) => (item.isEdit = false));
  row.isEdit = true;
  isEdit.value = true;
};
const onSave = async (row) => {
  const { paymentAmount, paymentTime, paymentFileUrl, itemName } = row || {};
  if (!itemName) return ElMessage.error("请输入款项名称");
  if (!paymentAmount) return ElMessage.error("请输入支付金额");
  if (!paymentTime) return ElMessage.error("请输入付款时间");
  if (!paymentFileUrl || !paymentFileUrl.length)
    return ElMessage.error("请上传支付凭证");
  if (props.onlyEdit) {
    return onSaveOne(row);
  }
  isEdit.value = false;
  row.key = row.key || Math.random() * 1000;
  row.isEdit = false;
};
const onCancel = (row) => {
  if (props.onlyEdit) {
    getMonthDetails();
  }
  row.isEdit = false;
};
//新增一条
const onAddOne = () => {
  dataSource.value.map((item) => {
    item.isEdit = false;
  });
  dataSource.value = [
    ...dataSource.value,
    { isEdit: true, paymentFileUrl: [], type: 'USER' },
  ];
  isEdit.value = true;
};
const onDeleteOne = async ({ id }) => {
  const { code } = await fixedInvestDeleteInvestDetail({ id });
  if (code != "200") return;
  ElMessage.success("删除成功");
  handleFinish(true);
  getMonthDetails();
};
//删除这一条
const onDelete = (row, idx) => {
  if(row.type === 'AUTO') return ElMessage.error("不可删除自动同步明细！");
  if (props.onlyEdit) return onDeleteOne(row);
  dataSource.value = dataSource.value.filter(
    (item, index) => index !== idx || item.id !== row.id
  );
  isEdit.value = false;
}

const handlePreview = (row) => {
  const [file] = row.paymentFileUrl || []
  if(row.type === 'USER') {
    if (!file) return ElMessage.error("请上传文件")
    previewUrl.value = file.url;
    previewVisible.value = true;
  }else {
    if (!file) return
    window.open(file.url, '_blank')
  }
}

const onSaveOne = async (row) => {
  const { paymentFileUrl: files = [], isEdit, key, ...rest } = row;
  const [file = {}] = files;
  const { name, url } = file;
  const { code } = await fixedInvestEditDetail({
    ...rest,
    paymentFileUrl: url,
    paymentFileName: name,
  });
  if (code != "200") return;
  ElMessage.success("保存成功");
  handleFinish(true);
  row.isEdit = false;
};
const onFinish = async () => {
  const abledDataSource = dataSource.value.filter((_) => !_.disabled);
  const addDataSource = abledDataSource.filter((_) => _.key);

  if (abledDataSource.length !== addDataSource.length)
    return ElMessage.error("请完善数据");

  await form.value?.validate();

  const details = dataSource.value.map((item) => {
    const { paymentFileUrl: files = [], isEdit, key, ...rest } = item;
    const [file = {}] = files;
    const { name, url } = file;
    return {
      ...rest,
      paymentFileUrl: url,
      paymentFileName: name,
    };
  });

  const { code } = await fixedInvestReport({
    details,
    ...edits.value,
    fixedProjectId: props.init.fixedProjectId,
    month: currentMonth.value,
    year: curYear,
  });
  if (code != "200") return;
  ElMessage.success("保存成功");
  handleFinish();
};
const handleFinish = (flag = false) => {
  emit("finish");
  open.value = flag;
};
const tableHeight = computed(() => {
  if (props.onlyEdit && dataSource.value.length > 4) return "50vh";
  else if (dataSource.value.length > 2) return "35vh";
  else return "100%";
});
</script>

<template>
  <CustomModal
    teleport="#app"
    width="70%"
    :title="title"
    v-model:visible="open"
    @on-confirm="onFinish"
    :footerButton="!props.onlyEdit"
  >
    <div class="modal_content">
      <el-form
        ref="form"
        label-position="left"
        label-width="auto"
        :model="edits"
        :rules="rules"
      >
        <div class="edit_title_tag">
          当前填报月份<b>{{ currentMonth }}</b
          >月
        </div>

        <div style="height: 15px"></div>
        <el-form-item>
          <CustomTable
            border
            :height="tableHeight"
            style="width: 100%"
            :tableData="dataSource"
            :tableOption.sync="columns"
            :isPaging="false"
            operation
            :operationWidth="200"
          >
            <template
              v-for="column in columns"
              #[column.prop]="scope"
              :key="column.prop"
            >
              <template v-if="!scope.row.isEdit">
                <el-button
                  v-if="column.prop === 'paymentFileUrl'"
                  :disabled="!scope.row?.paymentFileUrl.length"
                  link
                  @click="handlePreview(scope.row)"
                >
                  {{
                    scope.row?.paymentFileUrl?.length
                      ? scope.row?.type === 'USER' ? `预览（${scope.row?.paymentFileUrl[0]?.name}）` : '查看审批'
                      : "-"
                  }}
                </el-button>
                <span v-else-if="column.editType == 'inputNumber'">{{
                  transformNumber(scope.row[column.prop])
                }}</span>
                <span v-else>{{ scope.row[column.prop] || "-" }}</span>
              </template>

              <el-form-item v-else :prop="column.prop">
                <el-input
                  v-if="column.editType == 'input'"
                  v-model="scope.row[column.prop]"
                  :placeholder="`请输入${column.label}`"
                ></el-input>

                <el-input-number
                  style="width: 100%"
                  :controls="false"
                  v-if="column.editType == 'inputNumber'"
                  v-model="scope.row[column.prop]"
                  :placeholder="`请输入${column.label}`"
                ></el-input-number>
                <div
                  style="width: 100%; padding: 10px"
                  v-if="column.editType == 'upload'"
                >
                  <el-upload
                    ref="uploadRef"
                    :show-file-list="true"
                    :http-request="(e) => onUpload(e, scope.row)"
                    v-model:file-list="scope.row[column.prop]"
                  >
                    <el-button type="primary">上传凭证</el-button>
                  </el-upload>
                </div>

                <el-date-picker
                  v-if="column.editType == 'date'"
                  v-model="scope.row[column.prop]"
                  type="date"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  placeholder="选择付款时间"
                  size="large"
                />
                <!-- <span v-if="column.prop == 'type'">
                  {{ recordType[scope.row.type] }}
                </span> -->
              </el-form-item>
            </template>
            <template #menu="scope">
              <template v-if="!scope.row.disabled">
                <el-button
                  @click="onEdit(scope.row)"
                  v-if="
                    (userId == scope.row.createUserId || !props.onlyEdit) &&
                    !scope.row.isEdit
                  "
                  link
                  >修改</el-button
                >

                <template
                  v-else-if="
                    (userId == scope.row.createUserId || !props.onlyEdit) &&
                    scope.row.isEdit
                  "
                >
                  <el-button @click="onSave(scope.row)" link>保存</el-button>
                  <el-button
                    @click="onCancel(scope.row)"
                    v-if="scope.row.key || scope.row.fixedProjectId"
                    link
                    >取消</el-button
                  >
                </template>

                <el-popconfirm
                  v-if="!props.onlyEdit || userId == scope.row.createUserId"
                  title="确定要删除此条记录吗？"
                  @confirm="onDelete(scope.row, scope.$index)"
                >
                  <template #reference>
                    <el-button link type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </template>
          </CustomTable>
          <div v-if="!props.onlyEdit" class="add_btn">
            <el-button type="primary" @click="onAddOne" v-if="!isEdit"
              >新增一条</el-button
            >
          </div>
          <el-alert
            type="warning"
            :closable="false"
            description="温馨提示:支付凭证仅支持pdf/png/jpg/jpeg文件，且不超过1M"
          />
        </el-form-item>

        <template v-if="!props.onlyEdit">
          <el-form-item label="本月工作重点" prop="importantWork">
            <el-input type="textarea" v-model="edits.importantWork"></el-input>
          </el-form-item>
          <el-form-item label="下月工作安排" prop="nextMonthWork">
            <el-input type="textarea" v-model="edits.nextMonthWork"></el-input>
          </el-form-item>
        </template>
      </el-form>
    </div>
  </CustomModal>

  <el-dialog v-model="previewVisible">
    <div class="dialog_content">
      <img
        v-if="endsWithAny(previewUrl, ['.jpg', '.png', '.jpeg'])"
        style="width: 100%"
        w-full
        :src="previewUrl"
        alt="图片预览"
      />
      <PreviewPdf v-if="previewUrl.endsWith('.pdf')" :url="previewUrl" />
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
@import "@/styles/investPaper.scss";
</style>
